<template>
  <div>
    <div class="info-container">
      <div class="header">
        <img :src="imageUrl" class="update-header-image">
        <a href="javascript:void(0)" class="upload-link" @click="clickUploadHeader">点击上传</a>
      </div>
      <div class="userinfo-container">
        <div class="id">
          ID: <span>{{ user.userId }}</span>
        </div>
        <div class="meta-container">
          <div class="collection-count">
            评论 {{ comments }}
          </div>
          <div class="comment-count">
            收藏 {{ collections }}
          </div>
        </div>
        <a-divider />
        <div class="form-container">
          <a-spin tip="修改中请稍后" :spinning="updateInfoLoading">
            <a-form :form="updateForm" @submit="handleUpdateSubmit">
              <a-form-item label="账号: " :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                <a-input
                  v-decorator="[
                    'username',
                    {
                      rules: [
                        {
                          required: true,
                          message: '请输入账号'
                        },
                      ],
                      initialValue:user.username
                    },
                  ]"
                  :disabled="true"
                  placeholder="请输入账号"
                >
                  <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
                </a-input>
              </a-form-item>
              <a-form-item label="密码: " :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                <a-button type="primary" @click="openUpdatePasswordDialog">
                  修改密码
                </a-button>
              </a-form-item>
              <a-form-item label="昵称: " :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                <a-input
                  v-decorator="[
                    'nickname',
                    {
                      rules: [{ required: true, message: '请输入昵称', whitespace: true }],initialValue:user.nickname
                    },
                  ]"
                  placeholder="请输入昵称"
                >
                  <a-icon slot="prefix" type="meh" style="color: rgba(0,0,0,.25)" />
                </a-input>
              </a-form-item>
              <!--邮件-->
              <a-form-item label="邮箱: " :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                <a-input
                  v-decorator="['userEmail',{rules: [{type: 'email',message: '邮件不合法',},{required: true,message: '请输入邮件'}],initialValue:user.userEmail}]"
                  placeholder="请输入邮箱"
                >
                  <a-icon slot="prefix" type="mail" style="color: rgba(0,0,0,.25)" />
                </a-input>
              </a-form-item>
              <a-form-item label="性别: " :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                <a-radio-group v-decorator="['sex',{rules:[{required:true,message:'请选择性别'}],initialValue:user.sex+''}]">
                  <a-radio value="1">
                    男
                  </a-radio>
                  <a-radio value="0">
                    女
                  </a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item>
                <a-button type="primary" html-type="submit" class="register-button">
                  修改
                </a-button>
              </a-form-item>
            </a-form>
          </a-spin>
        </div>
      </div>
    </div>
    <!--修改密码-->
    <a-modal v-model="updatePasswordVisible" title="修改密码" ok-text="确认" cancel-text="取消" @ok="updatePassword">
      <a-form :form="updatePasswordForm">
        <a-form-item label="密码: " :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-input
            v-decorator="[
              'password',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入密码'
                  },
                  {
                    validator: validateToNextPassword,
                  },
                ]
              },
            ]"
            type="password"
            placeholder="请输入密码"
          >
            <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
          </a-input>
        </a-form-item>
        <a-form-item label="确认: " :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-input
            v-decorator="[
              'confirm',
              {
                rules: [
                  {
                    required: true,
                    message: '确认密码'
                  },
                  {
                    validator: compareToFirstPassword,
                  },
                ],
              },
            ]"
            type="password"
            placeholder="确认密码"
            @blur="handleConfirmBlur"
          >
            <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
          </a-input>
        </a-form-item>
      </a-form>
    </a-modal>
    <!--头像上传-->
    <a-modal v-model="uploadHeaderVisible" title="头像修改" ok-text="确认" cancel-text="取消" @ok="updatePassword">
      <a-upload-dragger
        name="file"
        :action="uploadUrl"
        :headers="headers"
        @change="handleChange"
      >
        <p class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </p>
        <p class="ant-upload-text">
          点击或拖拽图片上传
        </p>
      </a-upload-dragger>
    </a-modal>
  </div>
</template>

<script>
import userApi from '@/api/myuser'
import md5 from 'js-md5'
import { getToken } from '../../utils/auth'

export default {
  name: 'Info',
  data() {
    return {
      updateForm: this.$form.createForm(this),
      updatePasswordForm: this.$form.createForm(this),
      updatePasswordVisible: false,
      uploadHeaderVisible: false,
      user: this.$store.getters.getUser,
      comments: 0,
      collections: 0,
      confirmDirty: false,
      updateInfoLoading: false,
      uploadUrl: process.env.VUE_APP_UPLOAD_URL,
      headers: {
        Authorization: getToken()
      },
      imageUrl: this.$store.getters.getUser.header
    }
  },
  created() {
    this.getTotalCount()
  },
  methods: {
    // 图片上传
    handleChange(info) {
      const status = info.file.status
      if (status === 'done') {
        this.imageUrl = info.file.response.data
        this.uploadHeaderVisible = false
        if (status !== 'uploading') {
          console.log(info.file, info.fileList)
        }
        this.$message.success(`${info.file.name} 图片上传成功`)
      } else if (status === 'error') {
        this.$message.error(`${info.file.name} 图片上传失败`)
      }
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.form
      if (value && this.confirmDirty) {
        form.validateFields(['confirm'], { force: true })
      }
      callback()
    },
    handleConfirmBlur(e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.updatePasswordForm
      if (value && value !== form.getFieldValue('password')) {
        callback('两次密码不一样请重新输入!')
      } else {
        callback()
      }
    },
    getTotalCount() {
      userApi.getUserComments({}).then(res => {
        if (res.code === 200) {
          this.comments = res.data.countTotal
        }
      })
      userApi.getUserCollections({}).then(res => {
        if (res.code === 200) {
          this.collections = res.data.countTotal
        }
      })
    },
    /* 修改事件*/
    handleUpdateSubmit(e) {
      console.log(e)
      e.preventDefault()
      this.updateForm.validateFields((err, values) => {
        if (!err) {
          this.updateInfoLoading = true
          values.userId = this.user.userId
          values.header = this.imageUrl
          console.log(values)
          userApi.update(values).then(res => {
            if (res.code === 200) {
              this.$message.success(res.msg)
              this.updateInfoLoading = false
              this.$store.commit('SET_USER', res.data)
            } else {
              this.$message.error(res.msg)
              this.updateInfoLoading = false
            }
          }).catch(() => {
            this.updateInfoLoading = false
          })
        }
      })
    },
    // 点击上传图片弹窗
    clickUploadHeader() {
      this.uploadHeaderVisible = true
    },
    updatePassword() {
      var fieldValue = this.updatePasswordForm.getFieldValue('password')
      if (fieldValue) {
        var md = md5(fieldValue)
        this.user.password = md
        userApi.updatePassword(this.user).then(res => {
          if (res.code === 200) {
            this.$message.success(res.msg)
            this.updatePasswordVisible = false
          } else {
            this.$message.error(res.msg)
          }
        })
      }
    },
    openUpdatePasswordDialog() {
      this.updatePasswordVisible = true
    }
  }
}
</script>

<style lang="less" scoped>
.info-container{
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  .header{
    padding: 10px;
    .update-header-image{
      display: block;
      width: 100px;
      height: 100px;
      border-radius:50%;
      border: 3px solid #a2a2a2;
      box-shadow: 2px 0 15px #d6d6d6;
    }
    .upload-link{
      display: flex;
      justify-content: space-around;
      padding-top: 10px;
    }
  }
  .userinfo-container{
    padding: 10px;
    display: flex;
    flex-flow: column nowrap;
    margin-left: 20px;
    .id{
      font-size: 20px;
      color: #ba99a5;
    }
    .meta-container{
      display: flex;
      flex-flow: row nowrap;
      color: #a2a2a2;
      line-height: 40px;
    }
  }
}
</style>
